﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PlatformDemo
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            interfaces = Reflection.CreateAllInstancesOf<Interface>();

            InitializeComponent();

            TreeNode treeNode;
            foreach (var itfs in interfaces)
            {
                bool isHas = false;

                foreach (TreeNode item in treeView.Nodes)
                {
                    if (item.Level == 0 && itfs.Category == item.Text)
                    {
                        TreeNode value = new TreeNode(itfs.Name);
                        item.Nodes.Add(value);
                        isHas = true;
                        break;
                    }
                }

                if (!isHas)
                {
                    treeNode = new TreeNode(itfs.Category, new TreeNode[] { new TreeNode(itfs.Name) });
                    treeView.Nodes.Add(treeNode);
                }
            }

            treeView.DoubleClick += (object sender, EventArgs eventArgs) =>
            {
                treeNode = treeView.SelectedNode;
                var plugin = interfaces.Where(i => i.Name == treeNode.Text && treeNode.Level != 0).FirstOrDefault();
                if (plugin == null || plugin == currentInterface)
                    return;
                else currentInterface = plugin;

                DisposeCurrentInterface();
                var control = plugin.CreatePanel();
                control.Dock = DockStyle.Fill;
                demoContainer.Controls.Add(control);
            };

            FormClosing += (object sender, FormClosingEventArgs closingEventArgs) =>
            {
                DisposeCurrentInterface();
            };
        }

        private Interface currentInterface;
        private IEnumerable<Interface> interfaces;

        private void DisposeCurrentInterface()
        {
            if (demoContainer.Controls.Count <= 0) return;
            demoContainer.Controls[0].Dispose();
            demoContainer.Controls.Clear();
            GC.Collect();
        }
    }
}
